package com.summer.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.summer.common.ServerResponse;

/** 
 * @描述：简单的统一异常处理
 * @作者：yang 
 * @时间：2017年7月4日 上午10:16:13 
 * @版本：1.0
 */
@RestControllerAdvice
public class ExceptionAdvice {

	private Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
	
    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ServerResponse<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error("参数解析失败", e);
        return ServerResponse.createByErrorCodeMessage(400, "请求异常，服务器无法解析！");
    }

    /**
     * 404 - Not Found
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public ServerResponse<String> handleNoHandlerFoundException(NoHandlerFoundException e) {
        logger.error("404找不到请求路径", e);
        return ServerResponse.createByErrorCodeMessage(404, "找不到请求路径！");
    }
    
    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ServerResponse<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        logger.error("不支持当前请求方法", e);
        return ServerResponse.createByErrorCodeMessage(405, "不支持当前请求方法！");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public ServerResponse<String> handleHttpMediaTypeNotSupportedException(Exception e) {
        logger.error("不支持当前媒体类型", e);
        return ServerResponse.createByErrorCodeMessage(415, "不支持当前媒体类型！");
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ServerResponse<String> handleException(Exception e) {
        logger.error("服务运行异常", e);
        return ServerResponse.createByErrorCodeMessage(500, "服务器运行异常！");
    }
}
